/* eslint-disable max-lines */
/* eslint-disable react/jsx-max-depth */
import React, { useEffect, useState } from 'react';
import { connect, useDispatch } from 'umi';
import { Input, Button, Divider, message, Table, Popconfirm, Row, Col, Form, Modal, Tooltip, Alert } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import PageTopFormContent from '@/components/PageTopFormContent';
import PaginationCommon from '@/components/PaginationCommon';
import Ellipsis from '@/components/Ellipsis';
import UserGroupDetail from './components/UserGroupDetail';
import UserGroupAddEdit from './components/UserGroupAddEdit';
import styles from './UserGroupManage.less';

const { confirm } = Modal;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const UserManage = (props) => {
  const { userGroupManageModel, loading: { effects }} = props;
  const {
    userGroupList,
    userGroupListTotal,
  } = userGroupManageModel;

  const [currentPageNum, setCurrentPageNum] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [sort, setSort] = useState({ gmtCreated: 'desc' });
  const [formData, setFormData] = useState({});
  const [currentEditData, setCurrentEditData] = useState({});
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerType, setDrawerType] = useState('add');
  const [selectedRows, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [groupStateSearch, setGroupStateSearch] = useState();
  const [groupDetailData, setGroupDetailData] = useState(null);

  const dispatch = useDispatch();
  const [form] = Form.useForm();

  useEffect(() => {
    const updateTableData = () => {
      const currentData = {
        pageIndex: currentPageNum,
        pageSize: currentPageSize,
        sortMap: sort,
        groupState: groupStateSearch,
        ...formData,
      };
      dispatch({
        type: 'userGroupManageModel/getUserGroupList',
        payload: currentData,
      });
    };
    setSelectedRowKeys([]);
    setSelectedRows([]);
    updateTableData();
  }, [currentPageNum, currentPageSize, dispatch, formData, groupStateSearch, sort]);

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values };
      setFormData(param);
      setCurrentPageNum(1);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPageNum(1);
    setFormData({});
  };

  const handleShowEdit = (type, record) => {
    setDrawerType(type);
    setDrawerVisible(true);
    if (record) {
      setCurrentEditData(record);
    }
  };
  const handleCloseEdit = (updateFlag) => {
    setDrawerVisible(false);
    setCurrentEditData({});
    if (updateFlag === true) {
      handleSearch();
    }
  };

  const handleDel = (idList) => {
    dispatch({
      type: 'userGroupManageModel/deleteGroup',
      payload: idList,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('删除成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };

  const handleGoDetail = (record) => {
    setGroupDetailData(record);
  };

  const handleChangeUserState = (idsList, action) => {
    dispatch({
      type: `userGroupManageModel/${action === 'enable' ? 'enableGroup' : 'disableGroup'}`,
      payload: idsList,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success(`${action === 'enable' ? '启用' : '停用'}成功`);
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  };

  const handleBatchOpt = (optText) => {
    if (selectedRowKeys.length === 0) {
      message.warn(`请勾选要${optText}的用户组`);
      return false;
    }
    const nameList = [];
    const idList = [];
    selectedRows.forEach((item) => {
      nameList.push(item.groupName);
      idList.push(item.id);
    });
    confirm({
      title: nameList.length === 1
        ? `确定要${optText} ${nameList[0]} 人员组吗？`
        : `确定要批量${optText}选中的 ${nameList.length} 个人员组吗？`,
      onOk() {
        if (optText === '删除') {
          handleDel(idList);
        } else {
          handleChangeUserState(idList, optText === '启用' ? 'enable' : 'disable');
        }
      },
    });
    return true;
  };

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPageNum(page);
    setCurrentPageSize(pageSize);
  };

  const handleTableChange = (_, filters, sorter) => {
    const { groupState } = filters;
    if (JSON.stringify(sorter) !== '{}') {
      const { field, order } = sorter;
      setSort({
        [field]: order === 'ascend' ? 'asc' : 'desc',
      });
    }
    if (groupState && groupState.length === 1) {
      setGroupStateSearch(groupState[0]);
    } else {
      setGroupStateSearch('');
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeysParam, selectedRowsParam) => {
      setSelectedRowKeys(selectedRowKeysParam);
      setSelectedRows(selectedRowsParam);
    },
  };

  const columns = [
    {
      title: '人员组编码',
      width: 120,
      ellipsis: true,
      dataIndex: 'groupCode',
      key: 'groupCode',
    },
    {
      title: '人员组名称',
      dataIndex: 'groupName',
      key: 'groupName',
    },
    {
      title: '人员清单',
      dataIndex: 'employeeList',
      key: 'employeeList',
      render: (employeeList, record) => (
        <Ellipsis length={20} tooltip>
          {employeeList.map(u => u.employeeName).join('、')}
        </Ellipsis>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: {
        showTitle: false,
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '配置用户数',
      dataIndex: 'employeeCount',
      key: 'employeeCount',
    },
    {
      title: '更新人',
      dataIndex: 'modifierName',
      key: 'modifierName',
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      render: (record) => {
        const { id } = record;
        return (
          <div>
            <Button type="link" onClick={() => handleGoDetail(record)}>详情</Button>
            <Divider type="vertical" />
            <Button type="link" onClick={() => handleShowEdit('edit', record)}>修改</Button>
            <Divider type="vertical" />
            <Popconfirm
              title="确定要删除该人员组吗？"
              onConfirm={() => handleDel([id])}
            >
              <Button type="link">删除</Button>
            </Popconfirm>
          </div>
        );
      },
    },
  ];

  return (
    <>
      {groupDetailData !== null && (
        <UserGroupDetail
          onBack={() => {
            setGroupDetailData(null);
          }}
          groupDetailData={groupDetailData}
        />
      )}
      <div className={styles.root} style={{ display: groupDetailData !== null ? 'none' : 'initial' }}>
        <PageTopFormContent
          title="人员组管理"
          content={(
            <Form {...layout} form={form}>
              <Row gutter={[32, 16]}>
                <Col span={6}>
                  <Form.Item name="groupCodeKey" label="人员组编号">
                    <Input placeholder="请输入人员组编号" />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="groupNameKey" label="人员组名称">
                    <Input placeholder="请输入人员组名称" />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="employeeName" label="人员名称">
                    <Input placeholder="请输入人员名称" />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item wrapperCol={{ span: 24 }}>
                    <Button type="primary" onClick={handleSearch}>查询</Button>
                    <Button style={{ marginLeft: 16 }} onClick={handleReset}>重置</Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          )}
        />
        <div className={styles.bottomWrapper}>
          <div className={styles.rightTable}>
            <div className={styles.rightTableTop}>
              <div className={styles.left}>
                <div className={styles.title}>人员组列表</div>
              </div>
              <div className={styles.right}>
                {selectedRows.length > 0 &&
                  (
                    <Alert
                      style={{ display: 'inline-block', padding: '3px 8px' }}
                      message={
                        (
                          <>
                            已选择
                            {' '}
                            <span style={{ color: '#1890FF', fontWeight: 'bold' }}>{selectedRows.length}</span>
                            {' '}
                            项，用户组配置员工数覆盖总计：
                            <span style={{ color: '#1890FF', fontWeight: 'bold' }}>
                              {selectedRows.map(row => row.employeeList.length).reduce((prev, cur) => prev + cur, 0)}
                            </span>
                            <Button
                              type="link"
                              size="small"
                              onClick={() => {
                                setSelectedRows([]);
                                setSelectedRowKeys([]);
                              }}
                            >
                              清空
                            </Button>
                          </>
                        )
                      }
                      type="info"
                    />
                  )}
                <Button
                  onClick={() => handleBatchOpt('删除')}
                  type="danger"
                  disabled={selectedRows.length === 0}
                >
                  批量删除
                </Button>
                <Button type="primary" onClick={() => handleShowEdit('add')}>
                  <PlusOutlined />
                  新增
                </Button>
              </div>
            </div>
            <div className={styles.tableWrapper}>
              <Table
                rowKey="id"
                loading={effects['userGroupManageModel/getUserGroupList']}
                rowSelection={{
                  ...rowSelection,
                }}
                columns={columns}
                dataSource={userGroupList}
                pagination={false}
                onChange={handleTableChange}
              />
              <PaginationCommon
                total={userGroupListTotal}
                onChange={handlePaginationChange}
                current={currentPageNum}
                pageSize={currentPageSize}
                style={{ textAlign: 'right' }}
                showQuickJumper
                showSizeChanger
              />
            </div>
          </div>
        </div>
        {drawerVisible && (
          <UserGroupAddEdit
            editData={currentEditData}
            drawerType={drawerType}
            handleClose={handleCloseEdit}
          />
        )}
      </div>
    </>
  );
};

export default connect(state => state)(UserManage);
